package cn.iocoder.yudao.module.tms.service.customerfollowup;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.tms.controller.admin.customerfollowup.vo.*;
import cn.iocoder.yudao.module.tms.dal.dataobject.customerfollowup.CustomerFollowUpDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.tms.dal.mysql.customerfollowup.CustomerFollowUpMapper;
import cn.iocoder.yudao.module.tms.service.customerfollowlog.CustomerFollowLogService;
import cn.iocoder.yudao.module.tms.controller.admin.customerfollowlog.vo.CustomerFollowLogSaveReqVO;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.framework.common.biz.system.dict.dto.DictDataRespDTO;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.tms.enums.ErrorCodeConstants.*;

/**
 * 客户跟进 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class CustomerFollowUpServiceImpl implements CustomerFollowUpService {

    @Resource
    private CustomerFollowUpMapper customerFollowUpMapper;
    
    @Resource
    private CustomerFollowLogService customerFollowLogService;
    
    @Resource
    private DictDataApi dictDataApi;

    @Override
    public Long createCustomerFollowUp(CustomerFollowUpSaveReqVO createReqVO) {
        // 插入
        CustomerFollowUpDO customerFollowUp = BeanUtils.toBean(createReqVO, CustomerFollowUpDO.class);
        customerFollowUpMapper.insert(customerFollowUp);

        // 自动创建跟进日志
        createFollowLog(customerFollowUp.getId(), customerFollowUp.getCompanyId(), 
            "create", "新增客户跟进记录", 
            String.format("创建了客户跟进记录：%s", customerFollowUp.getCompanyName()));

        // 返回
        return customerFollowUp.getId();
    }

    @Override
    public void updateCustomerFollowUp(CustomerFollowUpSaveReqVO updateReqVO) {
        // 校验存在
        CustomerFollowUpDO oldData = validateCustomerFollowUpExists(updateReqVO.getId());
        
        // 更新
        CustomerFollowUpDO updateObj = BeanUtils.toBean(updateReqVO, CustomerFollowUpDO.class);
        customerFollowUpMapper.updateById(updateObj);
        
        // 生成变更对比内容
        String changeContent = generateChangeContent(oldData, updateObj);
        
        // 自动创建跟进日志
        createFollowLog(updateObj.getId(), updateObj.getCompanyId(), 
            "update", "更新客户跟进记录", changeContent);
    }

    @Override
    public void deleteCustomerFollowUp(Long id) {
        // 校验存在
        CustomerFollowUpDO customerFollowUp = validateCustomerFollowUpExists(id);
        
        // 自动创建跟进日志（在删除前记录）
        createFollowLog(id, customerFollowUp.getCompanyId(), 
            "delete", "删除客户跟进记录", 
            String.format("删除了客户跟进记录：%s", customerFollowUp.getCompanyName()));
        
        // 删除
        customerFollowUpMapper.deleteById(id);
    }

    @Override
    public void deleteCustomerFollowUpListByIds(List<Long> ids) {
        // 删除
        customerFollowUpMapper.deleteByIds(ids);
    }

    private CustomerFollowUpDO validateCustomerFollowUpExists(Long id) {
        CustomerFollowUpDO customerFollowUp = customerFollowUpMapper.selectById(id);
        if (customerFollowUp == null) {
            throw exception(CUSTOMER_FOLLOW_UP_NOT_EXISTS);
        }
        return customerFollowUp;
    }
    
    /**
     * 生成变更对比内容
     */
    private String generateChangeContent(CustomerFollowUpDO oldData, CustomerFollowUpDO newData) {
        StringBuilder content = new StringBuilder();
        content.append("<div style='line-height: 1.8;'>");
        content.append("<h4 style='margin: 0 0 10px 0; color: #409eff;'>📝 变更详情</h4>");
        content.append("<table style='width: 100%; border-collapse: collapse;'>");
        
        // 比较各个字段
        compareField(content, "公司名字", oldData.getCompanyName(), newData.getCompanyName());
        compareField(content, "公司地址", oldData.getCompanyAddress(), newData.getCompanyAddress());
        // 字典字段：公司模式
        compareDictField(content, "公司模式", "tms_company_mode", 
            oldData.getCompanyMode(), newData.getCompanyMode());
        compareField(content, "负责人", oldData.getPrincipal(), newData.getPrincipal());
        compareField(content, "访问人员", oldData.getVisitor(), newData.getVisitor());
        compareField(content, "走访时间", 
            oldData.getVisitTime() != null ? oldData.getVisitTime().toString() : null,
            newData.getVisitTime() != null ? newData.getVisitTime().toString() : null);
        compareField(content, "个人喜好", oldData.getPersonalPreference(), newData.getPersonalPreference());
        compareField(content, "业务量", oldData.getBusinessVolume(), newData.getBusinessVolume());
        compareField(content, "培训情况", oldData.getTrainingSituation(), newData.getTrainingSituation());
        compareField(content, "对方合作商", oldData.getPartner(), newData.getPartner());
        // 字典字段：跟进状态
        compareDictField(content, "跟进状态", "tms_follow_status", 
            oldData.getFollowStatus(), newData.getFollowStatus());
        compareField(content, "下次跟进时间",
            oldData.getNextFollowTime() != null ? oldData.getNextFollowTime().toString() : null,
            newData.getNextFollowTime() != null ? newData.getNextFollowTime().toString() : null);
        compareField(content, "备注", oldData.getRemark(), newData.getRemark());
        
        content.append("</table>");
        content.append("</div>");
        
        return content.toString();
    }
    
    /**
     * 比较字典字段
     */
    private void compareDictField(StringBuilder content, String fieldName, String dictType, 
                                   String oldValue, String newValue) {
        // 处理 null 值
        String oldVal = oldValue != null ? oldValue : "";
        String newVal = newValue != null ? newValue : "";
        
        // 只记录有变化的字段
        if (!oldVal.equals(newVal)) {
            // 获取字典标签
            String oldLabel = getDictLabel(dictType, oldVal);
            String newLabel = getDictLabel(dictType, newVal);
            
            content.append("<tr style='border-bottom: 1px solid #ebeef5;'>");
            content.append("<td style='padding: 8px; width: 120px; font-weight: 600; color: #606266;'>")
                   .append(fieldName).append("</td>");
            content.append("<td style='padding: 8px;'>");
            
            if (!oldVal.isEmpty()) {
                content.append("<span style='color: #f56c6c; text-decoration: line-through;'>")
                       .append(oldLabel).append("</span>");
            } else {
                content.append("<span style='color: #909399;'>（空）</span>");
            }
            
            content.append(" → ");
            
            if (!newVal.isEmpty()) {
                content.append("<span style='color: #67c23a; font-weight: 600;'>")
                       .append(newLabel).append("</span>");
            } else {
                content.append("<span style='color: #909399;'>（空）</span>");
            }
            
            content.append("</td>");
            content.append("</tr>");
        }
    }
    
    /**
     * 获取字典标签
     */
    private String getDictLabel(String dictType, String dictValue) {
        if (dictValue == null || dictValue.isEmpty()) {
            return "";
        }
        try {
            List<DictDataRespDTO> dictDataList = dictDataApi.getDictDataList(dictType);
            if (dictDataList != null) {
                for (DictDataRespDTO dictData : dictDataList) {
                    if (dictValue.equals(dictData.getValue())) {
                        return dictData.getLabel();
                    }
                }
            }
            // 如果没找到，返回原值
            return dictValue;
        } catch (Exception e) {
            // 如果获取失败，返回原值
            return dictValue;
        }
    }
    
    /**
     * 比较单个字段
     */
    private void compareField(StringBuilder content, String fieldName, String oldValue, String newValue) {
        // 处理 null 值
        String oldVal = oldValue != null ? oldValue : "";
        String newVal = newValue != null ? newValue : "";
        
        // 只记录有变化的字段
        if (!oldVal.equals(newVal)) {
            content.append("<tr style='border-bottom: 1px solid #ebeef5;'>");
            content.append("<td style='padding: 8px; width: 120px; font-weight: 600; color: #606266;'>")
                   .append(fieldName).append("</td>");
            content.append("<td style='padding: 8px;'>");
            
            if (!oldVal.isEmpty()) {
                content.append("<span style='color: #f56c6c; text-decoration: line-through;'>")
                       .append(oldVal).append("</span>");
            } else {
                content.append("<span style='color: #909399;'>（空）</span>");
            }
            
            content.append(" → ");
            
            if (!newVal.isEmpty()) {
                content.append("<span style='color: #67c23a; font-weight: 600;'>")
                       .append(newVal).append("</span>");
            } else {
                content.append("<span style='color: #909399;'>（空）</span>");
            }
            
            content.append("</td>");
            content.append("</tr>");
        }
    }
    
    /**
     * 创建跟进日志
     */
    private void createFollowLog(Long followUpId, Long companyId, String followType, 
                                  String followResult, String followContent) {
        try {
            CustomerFollowLogSaveReqVO logReqVO = new CustomerFollowLogSaveReqVO();
            logReqVO.setFollowUpId(followUpId);
            logReqVO.setCompanyId(companyId);
            logReqVO.setFollowType(followType);
            logReqVO.setFollowResult(followResult);
            logReqVO.setFollowContent(followContent);
            customerFollowLogService.createCustomerFollowLog(logReqVO);
        } catch (Exception e) {
            // 日志创建失败不影响主流程
            // 可以记录日志或进行其他处理
        }
    }

    @Override
    public CustomerFollowUpDO getCustomerFollowUp(Long id) {
        return customerFollowUpMapper.selectById(id);
    }

    @Override
    public PageResult<CustomerFollowUpDO> getCustomerFollowUpPage(CustomerFollowUpPageReqVO pageReqVO) {
        return customerFollowUpMapper.selectPage(pageReqVO);
    }

    @Override
    public List<CustomerFollowUpDO> getCustomerFollowUpListByCompanyId(Long companyId) {
        return customerFollowUpMapper.selectListByCompanyId(companyId);
    }

}
